package com.wx.oauth.utils;

import static com.wx.oauth.constants.WXConstants.*;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Chenhaowen
 * @since 2019/8/5 20:04.
 */
public class WXUtils {


    /**
     * 微信授权接口
     */
    private static String AUTHURL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";

    /**
     * 获取access_token的接口地址（get） 限2000（次/天）
     */
    private final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    /**
     * 获取jsapi_ticket的接口地址（GET） 限2000（次/天）
     */
    private final static String JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi";

    /**
     * 获取openId的接口地址
     */
    private final static String OAUTH_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";


    /**
     * 获取网页授权微信用户信息地址
     */
    private final static String SNS_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESSTOKEN&openid=OPENID&lang=zh_CN";

    /**
     * 获取微信卡券api_ticket 接口地址
     */
    private final static String API_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESSTOKEN&type=wx_card";


    private static final Logger logger = LoggerFactory.getLogger(WXUtils.class);


    public static String getOpenid(String APPID, String SECRET, String code) throws IOException {

        String access_token = "";
        String openid = "";
        System.out.println("1111"+code);
        String url = OAUTH_URL.replace("APPID",APPID).replace("SECRET",SECRET).replace("CODE",code);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = okHttpClient.newCall(request).execute();
        if(response.isSuccessful()){
            return response.body().string();
        }else{
            System.out.println("失败");
        }

        return "";
    }

    /**
     * 获取微信AccessToken
     * @return
     * @throws IOException
     */
    public static String getAccessTokenUrl() throws IOException {
        String accessTokenUrl = ACCESS_TOKEN_URL + "&appid=" + APPID + "&secret=" + APPSECRET;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(accessTokenUrl).build();
        Response response = okHttpClient.newCall(request).execute();
        System.out.println(accessTokenUrl);
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return "失败";
        }
    }





}
